package com.micro.ai.models.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.models.entity.ModelEvaluation;
import com.micro.ai.models.service.ModelEvaluationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 模型评估控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/model-evaluations")
@Tag(name = "模型评估管理", description = "模型评估的增删改查、启动")
public class ModelEvaluationController {

    @Autowired
    private ModelEvaluationService evaluationService;

    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('model:evaluation:create')")
    @Operation(summary = "创建评估", description = "创建新的模型评估任务")
    public ApiResponse<ModelEvaluation> create(@Valid @RequestBody ModelEvaluation evaluation) {
        log.info("创建模型评估请求: evalName={}", evaluation.getEvaluationName());
        evaluation.setCreatedBy(getCurrentUsername());
        ModelEvaluation result = evaluationService.create(evaluation);
        return ApiResponse.success("创建成功", result);
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('model:evaluation:view')")
    @Operation(summary = "获取评估详情", description = "获取模型评估详细信息")
    public ApiResponse<ModelEvaluation> getById(
            @Parameter(description = "评估ID", required = true) @PathVariable String id) {
        log.info("查询评估详情: evalId={}", id);
        
        ModelEvaluation evaluation = evaluationService.getById(id);
        if (evaluation == null) {
            return ApiResponse.error("404", "评估不存在");
        }
        
        return ApiResponse.success(evaluation);
    }

    @GetMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('model:evaluation:view')")
    @Operation(summary = "分页查询评估", description = "根据条件分页查询评估列表")
    public ApiResponse<Page<ModelEvaluation>> pageQuery(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "20") @RequestParam(defaultValue = "20") int pageSize,
            @Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
            @Parameter(description = "模型ID") @RequestParam(required = false) String modelId) {
        log.info("分页查询评估: pageNum={}, pageSize={}", pageNum, pageSize);
        
        Page<ModelEvaluation> page = evaluationService.pageQuery(pageNum, pageSize, tenantId, modelId);
        return ApiResponse.success(page);
    }

    @GetMapping("/by-model/{modelId}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('model:evaluation:view')")
    @Operation(summary = "获取模型的所有评估", description = "根据模型ID获取该模型的所有评估结果")
    public ApiResponse<Page<ModelEvaluation>> listByModelId(
            @Parameter(description = "模型ID", required = true) @PathVariable String modelId) {
        log.info("查询模型评估列表: modelId={}", modelId);
        
        Page<ModelEvaluation> page = evaluationService.listByModelId(modelId);
        return ApiResponse.success(page);
    }

    @PostMapping("/{id}/start")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('model:evaluation:update')")
    @Operation(summary = "启动评估", description = "启动模型评估任务")
    public ApiResponse<Void> start(
            @Parameter(description = "评估ID", required = true) @PathVariable String id) {
        log.info("启动评估请求: evalId={}", id);
        
        evaluationService.startEvaluation(id);
        return ApiResponse.successVoid("启动成功");
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('model:evaluation:update')")
    @Operation(summary = "更新评估", description = "更新模型评估信息")
    public ApiResponse<ModelEvaluation> update(
            @Parameter(description = "评估ID", required = true) @PathVariable String id,
            @Valid @RequestBody ModelEvaluation evaluation) {
        log.info("更新评估请求: evalId={}", id);
        
        ModelEvaluation result = evaluationService.update(id, evaluation);
        return ApiResponse.success("更新成功", result);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('model:evaluation:delete')")
    @Operation(summary = "删除评估", description = "删除模型评估")
    public ApiResponse<Void> delete(
            @Parameter(description = "评估ID", required = true) @PathVariable String id) {
        log.info("删除评估请求: evalId={}", id);
        
        evaluationService.delete(id);
        return ApiResponse.successVoid("删除成功");
    }

    private String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null ? authentication.getName() : "system";
    }
}

